<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ImportBankCheck extends Command
{
    private static array $errMsg = [];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:import-bank-check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入银行流水excel';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $url      = 'https://file.51kuafu.com/28/c2/37db358cfc809313a2eb5d14c9c5698a8a7bb5b99802466bc5d25bde7b89.xlsx';
        $pathInfo = parse_url($url);
        $client   = new Client();
        $tempData = $client->request("get", $url)->getBody()->getContents();
        $file     = md5($url) . date('YmdHis', time()) . "." . implode(".", $pathInfo)[1];
        Storage::disk("public")->put($file, $tempData);
        $import = Excel::toCollection(null, storage_path("app/public") . "/{$file}");
        Storage::disk("public")->delete($file);

        $import = $import->first()->filter(function ($item) {
            if ($item[0] === null) {
                return false;
            }

            return true;
        });

        OpenShopSignOrderPayHistoryModel::query()
                                        ->with([
                                            "signOrderRel" => function ($query) {
                                                $query->where('status', SignOrderEnum::ORDER_STATUS_OK);
                                            }
                                        ])
                                        ->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                        ->where('payChannel', OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE)
                                        ->where('payTime', '>=', 1648742400)
                                        ->groupBy('orderNo')
                                        ->select("orderNo", DB::raw("sum(payPrice) as payPrice"), 'id', 'subject',
                                            'createdAt')
                                        ->get()
                                        ->each(function ($item) use ($import) {

                                            if (!$item->signOrderRel) {
                                                return;
                                            }

                                            $dbName   = $item->signOrderRel->identityCardRel->name;
                                            $shopCode = $item->signOrderRel->shopCode;
                                            $isExport = $item->signOrderRel->orderType ? "是" : "-";
                                            $dbPrice  = $item->payPrice / 100;

                                            $importArr = $import->where(8, $dbName);
                                            if (!$importArr->count()) {
                                                self::$errMsg[] = [
                                                    $dbName,
                                                    $item->orderNo,
                                                    $shopCode,
                                                    $dbPrice,
                                                    0,
                                                    $item->createdAt->toDateTimeString(),
                                                    $isExport,
                                                    'excel中没有该用户的支付流水'
                                                ];
                                                return;
                                            }

                                            if ($importArr->sum(5) != $dbPrice && !$importArr->where(5, $dbPrice)
                                                                                             ->count()) {
                                                self::$errMsg[] = [
                                                    $dbName,
                                                    $item->orderNo,
                                                    $shopCode,
                                                    $dbPrice,
                                                    $importArr->sum(5),
                                                    $item->createdAt->toDateTimeString(),
                                                    $isExport,
                                                    '金额不对'
                                                ];
                                            }
                                        });

        dump(self::$errMsg);

        ini_set('max_execution_time', 100000);
        header("Content-Disposition: attachment; filename=" . urlencode('开店加盟费对账异常明细') . 'csv');

        // UTF8的BOM头
        $fd = fopen(public_path('/dc.csv'), 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        fputcsv($fd, [
            '姓名',
            '开店订单号',
            '门店编号',
            '应付加盟费',
            'excel支付金额',
            '开店订单支付时间',
            '是否为手动导入订单',
            '异常原因',
        ]);
        collect(self::$errMsg)->each(function ($item) use (&$fd) {
            fputcsv($fd, $item);
        });


        if (is_resource($fd)) {
            fclose($fd);
        }
        die;
    }
}
